import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { cloneDeep } from '@/utils/index'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_PROXY + process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 10 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['ytoken'] = getToken()
      config.headers['Content-Type'] = 'application/json;'
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data

    const { code, data, message } = res

    // 根据返回的code值来做不同的处理(和后端约定)
    if (code === 'A0230') {
      // 清除缓存
      // 跳转登录
      window.location.href = '/login'
      return
    }
    if (code && (code + '').includes('A')) {
      if (!data) {
        if (message) {
          Message.error(message)
        }
      } else {
        Message.error('未知错误')
      }
      return
    }
    switch (code + '') {
      case '401':
        // 清缓存

        if (window.location.pathname != '/login') {
          Message.error(message)
        } else {
          Message.error('未知错误，请重新登录')
        }
        removeToken()

        const pathname = window.location.pathname
        window.location.href = '/login?redirect=' + pathname
        return
      case '403':
      case '400':
      case '500':
        if (message) {
          Message.error(message)
        } else {
          Message.error('未知错误')
        }
        break
      default:
        break
    }

    // 初始化返回结果
    const resJSON = cloneDeep(res)

    // 有code
    if (code) {
      resJSON.status = code === '00000'
    } else {
      // 无code
      if (res) {
        resJSON.status = true
        resJSON.data = res
      } else {
        resJSON.status = false
        Message.error({
          title: '错误',
          message: message
        })
      }
    }
    return resJSON
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
